package ca.eloas.judging.rest.resources;

import ca.eloas.judging.model.CompetitionObject;
import ca.eloas.judging.model.JudgeObject;
import ca.eloas.judging.objectify.PersistenceService;
import ca.eloas.judging.rest.repositories.CompetitionRepository;
import ca.eloas.judging.rest.repositories.JudgeRepository;
import ca.eloas.judging.rest.security.AuthenticationAuthorizationService;
import ca.eloas.restsupport.ToMessageOperation;
import ca.eloas.restsupport.utils.BasicResource;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;

import javax.inject.Inject;
import javax.inject.Provider;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

import static ca.eloas.restsupport.operations.AddLink.addLink;
import static ca.eloas.restsupport.operations.AddProvidedLink.addThisLink;

/**
 * @author JP
 */
@Path("/boot")
public class BootResource extends BasicResource {

    @Inject
    private JudgeRepository judges;

    @Inject
    private CompetitionRepository competitions;

    @Inject
    private AuthenticationAuthorizationService authService;


    @GET
    @Path("/")
    public BootMessage boot() {

        if ( authService.isAuthenticated() )  {

            JudgeObject judge = judges.findByEmail(authService.getUser().getLoginName());
            CompetitionObject competition = competitions.listAll().iterator().next();

            return get(new Object(), BootMessage.class)
                    .runAll(
                            new SetUserInfo(authService),
                            addLink("competitions", "/competitions"),
                            addLink("sessions", "/sessions"),
                            addLink("logout", authService.getLogoutURL().toString()),
                            addLink("currentUser", "/judges/" + judge.getId()),
                            addLink("currentScores", "/judges/" + judge.getId() + "/competitions/" + competition.getId() + "/scores")
                    ).now();
        } else {

            return get(new Object(), BootMessage.class)
                    .runAll(
                            new SetUserInfo(authService),
                            addLink("competitions", "/competitions"),
                            addLink("sessions", "/sessions")
                    ).now();
        }
    }


    private static class SetUserInfo implements ToMessageOperation<Object, BootMessage> {

        private final AuthenticationAuthorizationService service;

        public SetUserInfo(AuthenticationAuthorizationService service) {
            this.service = service;
        }

        public void run(Object object, BootMessage bootMessage) {

            if (service.isAuthenticated()) {
                bootMessage.setUserName(service.getUser().getLoginName());

            }
        }
    }
}
